package com.warrior.superdata.mysql.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.warrior.superdata.constants.ResultCode;
import com.warrior.superdata.mysql.entity.ApiParam;
import com.warrior.superdata.mysql.mapper.ApiParamMapper;
import com.warrior.superdata.mysql.service.ApiParamService;
import com.warrior.superdata.exceptionhandler.ApplicationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description:
 * @ClassName: com.warrior.wisdom.machine.room.mysql.service.impl.ApiParamServiceImpl.java
 * @date: 2022/2/23 10:42
 * @author xujian
 */
@Service
@Slf4j
public class ApiParamServiceImpl extends ServiceImpl<ApiParamMapper, ApiParam> implements ApiParamService {

    @Override
    public void deleteByApiId(Integer apiId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("api_id", apiId);
        this.remove(queryWrapper);
    }

    @Override
    public void addList(Integer apiId, List<ApiParam> list){
        if(null != apiId && !CollectionUtils.isEmpty(list)){
            Set<String> paramNames = list.stream().map(ApiParam::getParamName).collect(Collectors.toSet());
            if(list.size() != paramNames.size()){
                throw new ApplicationException(ResultCode.FAIL_CODE, "参数名称有重复");
            }

            QueryWrapper<ApiParam> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("api_id", apiId).in("param_name", paramNames);
            List<ApiParam> datasourceDatas = this.list(queryWrapper);
            if (!CollectionUtils.isEmpty(datasourceDatas)) {
                throw new ApplicationException(ResultCode.FAIL_CODE, "参数名称有重复");
            }

            this.saveBatch(list);
        }
    }

}
